package org.linlinjava.litemall.db.service;

import org.linlinjava.litemall.db.dao.LitemallUserMapper;
import org.linlinjava.litemall.db.dao.LitemallUserSettlementMapper;
import org.linlinjava.litemall.db.domain.LitemallUser;
import org.linlinjava.litemall.db.domain.LitemallUserSettlement;
import org.linlinjava.litemall.db.domain.LitemallUserSettlementExample;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * @author zhenghui
 * @date 2020/6/15
 */
@Service
public class LitemallUserSettlementService {

    @Resource
    private LitemallUserSettlementMapper userSettlementMapper;

    public void add(Integer sharedUserId, String prevMonthEndDay, BigDecimal totalSettleAmount, BigDecimal totalReferralAmount) {
        LitemallUserSettlement userSettlement  = new LitemallUserSettlement();
        userSettlement.setUserId(sharedUserId);
        userSettlement.setMonth(prevMonthEndDay.substring(0,7));
        userSettlement.setSettlementAmount(totalSettleAmount);
        userSettlement.setReferralAmount(totalReferralAmount);
        userSettlement.setTotalAmount(totalSettleAmount.add(totalReferralAmount));

        LitemallUserSettlementExample example = new LitemallUserSettlementExample();
        example.or()
                .andUserIdEqualTo(userSettlement.getUserId())
                .andMonthEqualTo(userSettlement.getMonth())
                .andDeletedEqualTo(false);
        LitemallUserSettlement settlement = userSettlementMapper.selectOneByExample(example);
        if (settlement == null) {
            userSettlement.setCreateTime(LocalDateTime.now());
            userSettlement.setUpdateTime(LocalDateTime.now());
            userSettlementMapper.insert(userSettlement);
        } else {
            userSettlement.setId(settlement.getId());
            userSettlement.setUpdateTime(LocalDateTime.now());
            userSettlementMapper.updateByPrimaryKey(userSettlement);
        }
    }

}
